/* eslint-disable camelcase */

export function bufferColorTable(gl) {
  const vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

  const a_Position = gl.getAttribLocation(gl.program, 'a_Colors');
  gl.enableVertexAttribArray(a_Position);
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);

  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.5, 0.5, 0.5, 0.5]), gl.STATIC_DRAW);
}

export function drawBuffer(gl, vertices, key) {
  const vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

  const a_Position = gl.getAttribLocation(gl.program, key);
  gl.enableVertexAttribArray(a_Position);
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);

  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

  gl.clearColor(0.1, 0.1, 0.0, 0.1);
  gl.clear(gl.COLOR_BUFFER_BIT);
  const n = vertices.length / 2;
  gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
}

export const VSHADER_SOURCE = `
  attribute vec2 a_Position;
  void main() {
    gl_Position = vec4(a_Position, 0.0, 1.0);
  }
  `;

export const FSHADER_SOURCE = `
  precision mediump float;
  uniform float width;
  uniform float height;
  uniform float length;
  uniform sampler2D u_Palette;
  uniform sampler2D u_Sampler;
  vec2 reslution =vec2(width,height);

  highp float decode32(highp vec4 rgba) {
    highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;
    highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; 
    highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);
    highp float Result =  Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); 
    return Result;
}
 
  void main(){
      // gl_FragColor=vec4(gl_FragCoord.xyx/reslution.xyx,1.0);

      if(gl_FragCoord.y < 10.0){
        gl_FragColor=texture2D(u_Palette,gl_FragCoord.xy/reslution.xy);
      }
      else{
        vec4 color=texture2D(u_Sampler,vec2(gl_FragCoord.x,reslution.y-gl_FragCoord.y)/reslution.xy)*255.0;
        float val=decode32(color.abgr);
        if(val < -99.0){
          gl_FragColor=vec4(0.0,0.0,0.0,1.0);
        }
        else{
          gl_FragColor=texture2D(u_Palette,vec2((val+20.0)/100.0,1.0));
        }
      }
    }
  `;
